<template>
  <div>
    <el-row :gutter="20" v-if="type">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:project:device:add']" @click="openDialog(null)">增加</el-button>
<!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:project:device:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <!-- <el-row :gutter="20">
      <el-col :span="6"> -->
        <div class="grid-content bg-purple text">
          <span>设备总金额(元)：{{ allAmount }}</span>
        </div>
      <!-- </el-col>
    </el-row> -->

    <el-table
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="300"
      v-horizontal-scroll
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="产品名称"
        align="center"
      />
      <el-table-column
        property="type"
        label="产品属性"
        align="center"
        width="90"
      />
      <el-table-column
        property="product"
        label="标准产品"
        align="center"
      />
      <el-table-column
        property="deviceNo"
        label="型号"
        align="center"
      />
      <el-table-column
        property="num"
        label="数量"
        align="center"
      />
      <el-table-column
        property="amount"
        label="单价(元)"
        align="center"
      />
      <el-table-column
        property="totalAmount"
        label="总价(元)"
        align="center"
        width="120"
      />
      <el-table-column
        property="deliveryDate"
        label="交付日期"
        align="center"
      />
      <el-table-column
        property="guaranteeDate"
        label="质保日期"
        align="center"
      />
      <el-table-column
        property="contactName"
        label="联系人"
        align="center"
      />
      <el-table-column
        property="contactPhone"
        label="联系人电话"
        align="center"
      />
      <el-table-column
        property="clientName"
        label="所属客户"
        align="center"
      />
      <el-table-column
        property="facultyName"
        label="所属院系"
        align="center"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="100"
        v-if="type"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        width="160"
        sortable
        v-if="type"
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="type && ($auth.hasPermi('md:project:device:edit') || $auth.hasPermi('md:project:device:remove'))"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:project:device:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['md:project:device:remove']" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :autoScroll="false"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model.trim="form.name" :maxlength="50" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="产品属性" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="item in typeList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标准产品" prop="product" v-if="form.type === '自产'">
          <el-select v-model="form.product" clearable filterable placeholder="请选择标准产品" @change="selectChange" style="width: 100%;">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :value="item.productName"
            >
              <!-- :label="item.label" -->
              <span style="float: left">{{ item.productName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.productCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="deviceNo">
          <el-input v-model.trim="form.deviceNo" :maxlength="50" placeholder="请输入型号"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="form.num" :min="1" label="请输入数量" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="单价" prop="amount">
          <el-input
            v-model.trim="form.amount"
            :min="0"
            type="number" placeholder="请输入金额"
            @input="inputHandler"
            style="width: 100%"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-select
            v-model="form.contactName"
            allow-create
            clearable
            filterable
            placeholder="请选择联系人"
            style="width: 100%;"
            @change="contactChangeHandler"
          >
            <el-option
              v-for="item in contactList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input v-model.trim="form.contactPhone" clearable :maxlength="20" placeholder="请输入联系人电话"></el-input>
        </el-form-item>
        <el-form-item label="所属客户" prop="clientId" v-if="projectInfo.type === '代理商'">
          <el-select v-model="form.clientId" clearable filterable placeholder="请选择所属客户" @change="selectCustomerChange" style="width: 100%;">
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属院系" prop="facultyId" v-if="projectInfo.type === '代理商'">
          <el-select v-model="form.facultyId" clearable filterable placeholder="请选择所属院系" style="width: 100%;">
            <el-option
              v-for="item in schoolList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/md/project/device";
import { getDataListApi as getAllProductListApi } from "@/api/crm/md/product";
// import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import { getDataListApi as getAllCustomerApi } from "@/api/crm/md/customer";
import { getDataListApi as getContactListApi } from "@/api/crm/md/contacts";
import { getDataListApi as getAllSchoolApi } from "@/api/crm/md/school";
import { mapGetters } from 'vuex'

export default {
  name: 'ProjectDevice',
  dicts: ['sys_standard_products'],
  props: {
    projectInfo: {
      type: Object,
      required: true,
    },
    type: {
      type: Number,
      default: 1, // 1是全部功能 0是仅查看
    },
    change: {
      type: Function,
      default: () => {}
    },
  },
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      currentAmount: 0, // 当前预算金额
      allAmount: 0, // 总预算金额
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        clientId: "", // 客户id
        clientName: "", // 客户名称
        facultyId: "", // 院系id
        facultyName: "", // 院系名称
        product: "", // 标准产品
        type: "自产", // 产品属性
        deviceNo: "", // 设备型号
        totalAmount: "", // 总金额
        amount: "", // 金额
        createBy: "", // 用户
        createTime: "", // 创建时间
        id: null, // id
        name: "", // 设备名称
        num: 1, // 数量
        contactName: "", // 联系人名称
        contactPhone: "", // 联系人电话
        projectFundId: null, // 项目id
        projectName: "", // 项目名称
        remark: "", // 备注
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      typeList: [
        {
          value: "自产",
          label: "自产"
        },
        {
          value: "外购",
          label: "外购"
        },
      ],
      // 表单的校验规则
      rules: {
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请填写金额', trigger: 'blur' }
        ],
        deviceNo: [
          { required: true, message: '请填写型号', trigger: 'blur' }
        ],
        product: [
          { required: true, message: '请选择标准产品', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择产品属性', trigger: 'change' }
        ],
        num: [
          { required: true, message: '请填写数量', trigger: 'blur' }
        ],
      },
      // 表格数据
      tableData: [],
      // 联系人数据
      contactList: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        projectFundId: null, // 项目id
        name: "", // 设备名称
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 产品信息
      productList: [],
      // 客户列表
      customerList: [],
      // 院系列表
      schoolList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
    projectInfo: {
      deep: true,
      immediate: true,
      handler(newV) {
        this.queryParams.projectFundId = newV.id
        this.searchHandler()
        const type = newV.type === '客户' ? 0 : 1
        if(type) {
          this.getContactList(newV.agentId, type)
        } else {
          this.getContactList(newV.facultyId, type)
        }
      },
    },
  },
  created() {
    // this.provinceList = ProvinceData
    this.queryParams.projectFundId = this.projectInfo.id
    // this.getList()
    this.getUserinfo()
    this.getAllProductList()
    this.getCustomerList()
  },
  methods: {
    // 选择客户
    selectCustomerChange(val) {
      this.getAllSchoolList(val)
    },
    // 获取全部院系
    getAllSchoolList(clientId) {
      getAllSchoolApi({
        clientId
      }).then((res) => {
        if (res.code === 200) {
          this.schoolList = res.rows ?? []
        }
      })
    },
    // 获取全部客户
    getCustomerList() {
      getAllCustomerApi({
        flag: true,
      }).then((res) => {
        if (res.code === 200) {
          this.customerList = res.rows ?? []
        }
      })
    },
    // 选择标准产品
    selectChange(val) {
      let code = ""
      for (let i = 0; i < this.productList.length; i++) {
        const element = this.productList[i];
        if(element.productName.localeCompare(val) === 0) {
          code = element.productCode
          break
        }
      }

      this.form.deviceNo = code
    },
    // 获取全部标准产品
    async getAllProductList() {
      const res = await getAllProductListApi({})
      if(res.code === 200) {
        const list = (res.rows ?? [])

        list.unshift({
          id: -1,
          productName: "无",
          productCode: "无"
        })

        this.productList = list
      }
    },
    // 选择联系人的回调
    contactChangeHandler(val) {
      let phone = ""
      this.contactList.map((item) => {
        if(item.name.localeCompare(val) === 0) phone = item.phone
      })

      this.form.contactPhone = phone
    },
    // 获取联系人信息
    getContactList(clientAgentId, type) {
      getContactListApi({
        clientAgentId,
        type
      })
        .then((res) => {
          this.contactList = res.rows ?? []
        })
        .catch(() => {})
    },
    // 用户输入的回调
    inputHandler(e) {
      if(+e < 0) this.form.amount = 0
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const { code, data } = await getDataListApi(this.queryParams)
      if(code === 200) {
        this.tableData = data?.list?.rows ?? []
        this.total = data?.list?.total ?? 0

        this.allAmount = data?.bidAmount ?? 0

        this.currentAmount = this.tableData.reduce((acc, cur) => acc + (cur.amount ?? 0), 0)
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        row.clientId && this.getAllSchoolList(row.clientId)
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/device/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `devices_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.totalAmount = (+this.form.num) * (+this.form.amount)
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
        projectFundId: this.projectInfo.id,
        // type: 1,
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
        projectFundId: this.projectInfo.id,
        // type: 1,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    }
  },
}
</script>
<style scoped lang="scss">
.grid-content.text{
  margin-top: 10px;
  color: red;
}
</style>
